
#ifndef HELP_AIDER_HPP
#define HELP_AIDER_HPP

#include    <sys/types.h>
#include    <sys/stat.h>
#include    <sys/time.h>
#include    <unistd.h>
#include    <string.h>
#include    <errno.h>

namespace   help
{
    
class   Aider
{

public  :

    static  const char*     dirname( const char* pszPath )
    {
        static char     s_szDir[256];
        
        const char* pszSlash = strrchr(pszPath, '/');
        if (NULL == pszSlash) {
            return  NULL;
        }
        
        if (pszSlash == pszPath) {
            return  NULL;
        }
        if ((pszSlash - pszPath) > sizeof(s_szDir)) {
            return  NULL;
        }
        
        strncpy( s_szDir, pszPath, pszSlash - pszPath);
        
        return  s_szDir;
    }
    
    static  int makedir ( const char* pszPath )
    {
        char    szPath [ 1024 ];
        const char* p = pszPath;
        
        memset ( szPath, 0, sizeof(szPath) );
        
        while (*p)
        {
            if ('/' == *p)
            {
                if (pszPath == p)
                {
                    // root dir
                    // skip it
                    ++p;
                    continue;
                }
            
                strncpy ( szPath, pszPath, p - pszPath );
                if (0 == ::access( szPath, F_OK))
                {
                    // directory or file exists
                    ++p;
                    continue;
                }
                
                // directory doesNOT exists
                int iReturn = ::mkdir ( szPath, 0777 );
                if (iReturn < 0)
                {
                    fprintf(stderr, "Fail to mkdir '%s' for path '%s'", szPath, pszPath );
                    return  -1;
                }
            }
            
            ++p;
        }
        
        if (0 != ::access( pszPath, F_OK))
        {
            // directory doesNOT exists
            int iReturn = ::mkdir ( pszPath, 0777 );
            if (iReturn < 0)
            {
                fprintf(stderr, "Fail to mkdir '%s' : %s", pszPath, strerror(errno) );
                return  -1;
            }
        }
        
        return  0;
    }
    
    static    const char*     getTimeString ( void )
    {
        struct tm*  tmp;
        time_t  t;
        int     iReturn;
        
        static char     s_szBuf[128];
        int     iBufSize = sizeof(s_szBuf) - 1;
        char*   pszBuf = s_szBuf;
        
        pszBuf[0] = '\0';
        
        t = time (NULL);
        tmp = localtime( &t );
        if ( NULL == tmp ) {
            return  NULL;
        }
        
        pszBuf[0] = '\0';
        iReturn = strftime(pszBuf, iBufSize, "%Y-%m-%d %H:%M:%S", tmp);
        if (iReturn > 0) {
            pszBuf[ iReturn ] = '\0';
        }
        
        return  pszBuf;
    }   
    
};  // class    Aider

}   // namespace help


#endif  // HELP_AIDER_HPP
